<template>
	<div class="bgc-default">
		<div class="circle-x-tab pad-l-20 pad-r-20 pad-t-20">
			<el-form :model="entity" ref="form" label-width="170px" :rules="rules" class="pad-t-1">

				<el-form-item label="微客ID:">
					<div class="font-14 pad-l-10">
						<div v-if="entity.commanderId > 0 && entity.memberId > 0">{{entity.memberId}}</div>
						<div v-else>
							<span style="color: red;">到列表绑定微客</span>
						</div>
					</div>
				</el-form-item>

				<el-form-item label="团长信息:">
					<div class="flex v-align-c cursor-p" v-if="entity.commanderId > 0 && entity.memberId > 0">
						<label><img :src="entity.avatar" class="user-avatar" v-if="entity.avatar"></label>
						<div class="font-14 pad-l-10">
							<div>昵称：{{ entity.nickname}}</div>
							<div>姓名：{{ entity.realName}}</div>
							<div>手机：{{ entity.phone}}</div>
						</div>
					</div>
					<div v-else>
						<span style="color: red;">到列表绑定微客</span>
					</div>
				</el-form-item>
				<el-form-item label="店铺名称：">
					<el-input style="width: 300px;" placeholder="请输入店铺名称" v-model="entity.nickname"></el-input>
				</el-form-item>
				<el-form-item label="团长手机：">
					<el-input style="width: 300px;" placeholder="请输入团长手机号" class="mar-b-3" v-model="entity.phone">
					</el-input>
					</el-input>
				</el-form-item>
				<el-form-item label="提货点照片：" prop="takeAddressPicUrl">
					<div class="width-155">
						<el-upload list-type="picture-card" action="/api/common/uploadFiles"
							accept="image/jpeg, image/gif, image/png, image/bmp" name="files" :data="token"
							:show-file-list="false" v-loading="fileLoading"
							:on-success="handleUploadTakeAddressPicSuccess" :before-upload="beforeUploadTakeAddressPic">
							<img v-if="entity.takeAddressPicUrl" :src="entity.takeAddressPicUrl" class="img-box" />
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</div>
					<div class="font-12 font-color-9">建议尺寸750*750像素（1:1），小于3M，支持jpg、png、jpg格式。</div>
				</el-form-item>

				<el-form-item label="提货点名称：" prop="takeName">
					<el-input v-model="entity.takeName" class="long-input" placeholder="最多输入20个字" maxlength="20"
						show-word-limit />
				</el-form-item>

				<el-form-item label="有无门店：" prop="isHasStore">
					<el-radio-group v-model="entity.isHasStore" @change="changeIsHasStore"
						:disabled="entity.commanderId > 0  && entity.memberId > 0? true: false">
						<el-radio :label="1">有门店</el-radio>
						<el-radio :label="0">无门店</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="提货点类型：" prop="takeTypeId">
					<el-select v-model="entity.takeTypeId" placeholder="请选择自提点类型" @change="changeTakeType">
						<el-option v-for="item in takeTypeList" v-if="item.takeTypeCategoryId != 2"
							:key="item.takeTypeId" :label="item.takeTypeName" :value="item.takeTypeId">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="提货点地址：" prop="selectPCDValue">
					<AddressSelect ref="addressSelectRef" :onChangeAddressCode="onChangeAddressCode"></AddressSelect>
				</el-form-item>
				<el-form-item prop="takeAddress">
					<el-input v-model="entity.takeAddress" placeholder="详细地址(请勿重复填写省市区)"></el-input>
				</el-form-item>

				<el-form-item label="自定义范围:">
					<MapDeliveryRange ref="deliveryRangeRef" :onConfirm="handleConfirm"
						:onCustomDeliveryRange="handleCustomDeliveryRange"
						:onHandleIsCustomDeliveryRange="onHandleIsCustomDeliveryRange"
						:onHandleSetCustomDeliveryRange="onHandleSetCustomDeliveryRange"></MapDeliveryRange>
				</el-form-item>

				<el-form-item label="营业执照：" v-if="entity.isHasStore == 1" prop="businessLicensePicUrl">
					<div class="width-155">
						<el-upload list-type="picture-card" action="/api/common/uploadFiles"
							accept="image/jpeg, image/gif, image/png, image/bmp" name="files" :data="token"
							:show-file-list="false" v-loading="fileLoadingBusinessLicensePic"
							:on-success="handleUploadBusinessLicensePicSuccess"
							:before-upload="beforeUploadBusinessLicensePic">
							<img v-if="entity.businessLicensePicUrl" :src="entity.businessLicensePicUrl"
								class="img-box" />
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</div>
					<div class="font-12 font-color-9">建议尺寸300*420像素（1:1），小于3M，支持jpg、png、jpg格式。</div>
				</el-form-item>

				<el-form-item label="身份证：" prop="selectIdCardValue">
					<div class="flex">
						<div class="width-155">
							<el-upload list-type="picture-card" action="/api/common/uploadFiles"
								accept="image/jpeg, image/gif, image/png, image/bmp" name="files" :data="token"
								:show-file-list="false" v-loading="fileLoadingIdCardPortraitPhoto"
								:on-success="handleUploadIdCardPortraitPhotoSuccess"
								:before-upload="beforeUploadIdCardPortraitPhoto">
								<img v-if="entity.idCardPortraitPhotoUrl" :src="entity.idCardPortraitPhotoUrl"
									class="img-box" />
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
							<div class="close-icon width-36 height-36 flex flex-center cursor-p"
								@click="closeEls('photoUrl')">
								<svg-icon v-if="entity.idCardPortraitPhotoUrl" icon-class="close"
									class="icon font-16 noraml-hide active" />
							</div>
						</div>
						<div class="width-155">
							<el-upload list-type="picture-card" action="/api/common/uploadFiles"
								accept="image/jpeg, image/gif, image/png, image/bmp" name="files" :data="token"
								:show-file-list="false" v-loading="fileLoadingIdCardNationalEmblemPic"
								:on-success="handleUploadIdCardNationalEmblemPicSuccess"
								:before-upload="beforeUploadIdCardNationalEmblemPic">
								<img v-if="entity.idCardNationalEmblemPicUrl" :src="entity.idCardNationalEmblemPicUrl"
									class="img-box" />
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
							<div class="close-icon width-36 height-36 flex flex-center cursor-p"
								@click="closeEls('picUrl')">
								<svg-icon v-if="entity.idCardNationalEmblemPicUrl" icon-class="close"
									class="icon font-16 noraml-hide active" />
							</div>
						</div>
					</div>

					<div class="font-12 font-color-9">建议尺寸300*420像素（1:1），小于3M，支持jpg、png、jpg格式。</div>
				</el-form-item>

				<el-form-item label="所属招募员:">
					<div class="font-14 pad-l-10">
						<div>姓名：{{ entity.recruiterName}}</div>
						<div>手机：{{ entity.recruiterPhone}}</div>
					</div>
				</el-form-item>

				<el-form-item label="所属上级:">
					<div class="font-14 pad-l-10">
						<div>姓名：{{ entity.recruiterParentName}}</div>
						<div>类型：{{ entity.recruiterParentTypeName}}</div>
					</div>
				</el-form-item>

			</el-form>
		</div>
		<div class="bottom-bar">
			<el-button @click="$router.go(-1)">返回</el-button>
			<el-button class="mar-l-30" type="primary" @click="saveData">保存</el-button>
		</div>
	</div>
</template>

<script>
	import {
	  getVillageCommander,
	  listByCommanderId,
	  saveCommander
	} from '@/api/user/commander'
	import elDragDialog from '@/directive/el-dragDialog'
	import {
	  getToken
	} from '@/utils/auth'
	import {
	  getTakeLocationTypeList
	} from '@/api/system/takeLocationType'
	import MapDeliveryRange from '@/components/MapDeliveryRange/index'
	import AddressSelect from '@/components/AddressSelect/index'
	export default {
	  directives: {
	    // 拖动窗口
	    elDragDialog
	  },
	  components: {
	    MapDeliveryRange,
	    AddressSelect
	  },
	  data() {
	    // 自定义地址验证规则
	    var addressRule = (rule, value, callback) => {
	      // console.log(this.entity.provinceCode)
	      // console.log(this.entity.cityCode)
	      // console.log(this.entity.districtCode)
	      // value 就是 验证那个字段 为空 或者 selectCityValue 为空 验证都不会通过
	      if (!this.entity.provinceCode || !this.entity.cityCode || !this.entity.districtCode) {
	        return callback(new Error('提货点地址不能为空！'))
	      } else {
	        callback()
	      }
	    }

	    return {
	      token: '',
	      entity: {
	        provinceCode: '',
	        cityCode: '',
	        districtCode: '',
	        takeAddress: ''
	      },
	      commanderId: '',
	      villageNames: '',
	      selectedDistrictCode: '',
	      dialogPickVillageVisible: false,
	      villageList: [],
	      villages: [],
	      listLoading: false,
	      dialogMapVisible: false,
	      loc: null,
	      fileLoading: false,
	      fileLoadingBusinessLicensePic: false,
	      fileLoadingIdCardPortraitPhoto: false,
	      fileLoadingIdCardNationalEmblemPic: false,
	      takeTypeList: [],
	      rules: {
	        takeAddressPicUrl: [{
	          required: true,
	          message: '提货点照片不能为空',
	          trigger: 'change'
	        }],
	        takeTypeId: [{
	          required: true,
	          message: '提货点类型不能为空',
	          trigger: 'change'
	        }],
	        takeName: [{
	          required: true,
	          message: '提货点名称不能为空',
	          trigger: 'blur'
	        }],
	        selectPCDValue: [{
	          required: true,
	          validator: addressRule,
	          trigger: 'change'
	        }],
	        takeAddress: [{
	          required: true,
	          message: '详细地址不能为空',
	          trigger: 'blur'
	        }],
	        businessLicensePicUrl: [{
	          required: true,
	          message: '营业执照不能为空',
	          trigger: 'change'
	        }],
	        isHasStore: [{
	          required: true,
	          message: '有无门店不能为空',
	          trigger: 'change'
	        }]
	      },
	      deliveryRangeList: [],
	      isCustomDeliveryRange: '0'
	    }
	  },
	  watch: {

	  },
	  mounted() {

	  },
	  // 初始化页面
	  created() {
	    this.token = {
	      accessToken: getToken()
	    }
	    const queryParams = this.getCurrentPage().query
	    if (queryParams && queryParams.commanderId) {
	      this.commanderId = queryParams.commanderId
	    }
	    this.init()
	  },
	  methods: {
	    closeEls(item) {
	      if (item === 'picUrl') {
	        this.entity.idCardNationalEmblemPicUrl = ''
	      }
	      if (item === 'photoUrl') {
	        this.entity.idCardPortraitPhotoUrl = ''
	      }
	    },
	    getTakeTypeList() {
	      getTakeLocationTypeList(this.entity.isHasStore).then(response => {
	        this.takeTypeList = response
	      })
	    },
	    init() {
	      if (this.commanderId && this.commanderId > 0) {
	        getVillageCommander(this.commanderId).then(response => {
	          if (response.isError) return
	          this.entity = response.data
	          this.deliveryRangeList = this.entity.deliveryRangeList
	          // 初始化省市区
	          this.$refs.addressSelectRef.setData(this.entity.provinceCode, this.entity.cityCode, this
	            .entity
	            .districtCode)
	          // 初始化是否自定义配送范围
	          this.$refs.deliveryRangeRef.setData(this.entity.isCustomAddress)
	          // 自提点类型列表
	          this.getTakeTypeList()
	        })

	        listByCommanderId({
	          commanderId: this.commanderId
	        }).then(response => {
	          if (response.isError) return
	          this.villageList = response.data
	        })
	      } else {
	        this.entity.enterpriseId = this.getEnterpriseId()
	        this.entity.isHasStore = 0
	        // 自提点类型列表
	        this.getTakeTypeList()
	      }
	    },
	    // 切换有无门店
	    changeIsHasStore(label) {
	      this.getTakeTypeList(label)
	      this.$set(this.entity, 'takeTypeId', undefined)
	    },
	    changeTakeType(val) {
	      this.$set(this.entity, 'takeTypeId', val)
	      this.$forceUpdate()
	    },
	    // 保存用户信息
	    saveData() {
	      console.log(this.entity)
	      this.$refs['form'].validate((valid) => {
	        if (valid) {
	          saveCommander(this.entity).then((response) => {
	            if (response.isError) return
	            this.$message({
	              type: 'success',
	              message: '保存成功!'
	            })
	            this.$router.go(-1)
	          })
	        }
	      })
	    },
	    // 文件上传前校验
	    beforeUpload(file, type) {
	      console.log(type)
	      const isJPG = file.type === 'image/jpeg'
	      const isGIF = file.type === 'image/gif'
	      const isPNG = file.type === 'image/png'
	      const isBMP = file.type === 'image/bmp'
	      if (!isJPG && !isGIF && !isPNG && !isBMP) {
	        this.$message({
	          type: 'error',
	          message: '上传图片必须是JPG/GIF/PNG/BMP 格式!'
	        })
	      } else {
	        if (type === 1) {
	          this.fileLoading = true
	        } else if (type === 2) {
	          this.fileLoadingBusinessLicensePic = true
	        } else if (type === 3) {
	          this.fileLoadingIdCardPortraitPhoto = true
	        } else if (type === 4) {
	          this.fileLoadingIdCardNationalEmblemPic = true
	        }
	      }
	      return (isJPG || isBMP || isGIF || isPNG)
	    },
	    beforeUploadTakeAddressPic(file) {
	      return this.beforeUpload(file, 1)
	    },
	    beforeUploadBusinessLicensePic(file) {
	      return this.beforeUpload(file, 2)
	    },
	    beforeUploadIdCardPortraitPhoto(file) {
	      return this.beforeUpload(file, 3)
	    },
	    beforeUploadIdCardNationalEmblemPic(file) {
	      return this.beforeUpload(file, 4)
	    },
	    handleUploadTakeAddressPicSuccess(res, file) {
	      this.fileLoading = false
	      if (res.code === 101) {
	        this.entity.takeAddressPicUrl = res.data[0]
	      } else {
	        this.$message({
	          type: 'error',
	          message: res.msg
	        })
	      }
	    },
	    handleUploadBusinessLicensePicSuccess(res, file) {
	      this.fileLoadingBusinessLicensePic = false
	      if (res.code === 101) {
	        this.$set(this.entity, 'businessLicensePicUrl', res.data[0])
	      } else {
	        this.$message({
	          type: 'error',
	          message: res.msg
	        })
	      }
	    },
	    handleUploadIdCardPortraitPhotoSuccess(res, file) {
	      this.fileLoadingIdCardPortraitPhoto = false
	      if (res.code === 101) {
	        this.$set(this.entity, 'idCardPortraitPhotoUrl', res.data[0])
	      } else {
	        this.$message({
	          type: 'error',
	          message: res.msg
	        })
	      }
	    },
	    handleUploadIdCardNationalEmblemPicSuccess(res, file) {
	      this.fileLoadingIdCardNationalEmblemPic = false
	      if (res.code === 101) {
	        this.$set(this.entity, 'idCardNationalEmblemPicUrl', res.data[0])
	      } else {
	        this.$message({
	          type: 'error',
	          message: res.msg
	        })
	      }
	    },
	    // 省市区改变监听的方法
	    onChangeAddressCode(pCode, cCode, dCode) {
	      this.entity.provinceCode = pCode
	      this.entity.cityCode = cCode
	      this.entity.districtCode = dCode
	      this.entity.takeAddress = ''
	    },
	    // 回调函数，确认已画好的配送范围，参数也会为空
	    handleConfirm(deliveryRangeList) {
	      this.entity.deliveryRangeList = deliveryRangeList
	    },
	    // 点击切换是否自定义配送范围
	    onHandleIsCustomDeliveryRange(e) {
	      this.$refs.deliveryRangeRef.initIsCustomDeliveryRange(this.getAddressDetail(), e)
	    },
	    // 切换是否自定义配送范围 回调函数
	    handleCustomDeliveryRange(isCustomDeliveryRange) {
	      this.entity.isCustomAddress = isCustomDeliveryRange
	      if (isCustomDeliveryRange === '0') {

	        // this.entity.deliveryRangeList = []
	      }
	      console.log('是否自定义范围：' + this.entity.isCustomAddress)
	    },
	    // 点击设置
	    onHandleSetCustomDeliveryRange() {
	      this.$refs.deliveryRangeRef.initCustomDeliveryRange(this.$refs.addressSelectRef.getCityName(), this
	        .getAddressDetail(), this.deliveryRangeList)
	    },
	    // 获取地址
	    getAddressDetail() {
	      var address = ''
	      var pcdName = this.$refs.addressSelectRef.getPCDName()
	      if (pcdName && this.entity.takeAddress) {
	        address = pcdName + this.entity.takeAddress
	      }
	      return address
	    }
	  }
	}
</script>
<style lang="less" scoped>
	.circle-x-tab {
		padding-bottom: 70px;
	}

	.des-box {
		background: #f3f3f3;
		margin: 15px;
		padding: 25px;

		.balance-list {
			&:last-child {
				margin-top: -10px;
				margin-bottom: -10px;
			}
		}

		.time-input {
			width: 100%;
		}

		.bottom-btn {
			padding-left: 130px;
			padding-top: 15px;
		}
	}

	.mission-type {
		padding: 35px 38px;
		min-width: 150px;
		border: 1px solid #dcdcdc;
		border-radius: 8px;
		margin: 25px 40px;
		cursor: pointer;
		text-align: center;
		box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
	}

	.flex-cag-box {
		padding: 0px 0px 20px 70px;

		.mission-type:nth-child(4n) {
			margin-right: 0px;
		}
	}

	.next-step-btn {
		padding: 13px 35px;
		font-size: 18px;
	}

	.sel-mission-type {
		background-color: #409eff;
		color: #fff;
	}

	.budget-el-select {
		padding-top: 10px;
		padding-left: 50px;
	}

	.user-avatar {
		width: 46px;
		height: 46px;
		display: block;
		border-radius: 50px;
	}

	.img-box {
		width: 150px;
		height: 150px;
	}

	.selectMap {
		display: flex;
		align-items: center;
		justify-content: center;

		/deep/.el-dialog {
			margin: 0 !important;
		}

		.s-result {
			height: 200px;
			overflow-y: scroll;
		}
	}

	.search-input {
		width: 96%;
		margin: 0 auto;
		display: block;

		/deep/ .el-input__inner {
			background-color: #f5f5f5;
		}
	}

	#toolControl {
		position: absolute;
		top: 135px;
		left: 50%;
		transform: translate(-50%);
		z-index: 1001;
	}

	.toolItem {
		width: 30px;
		height: 30px;
		float: left;
		margin: 1px;
		padding: 4px;
		border-radius: 3px;
		background-size: 30px 30px;
		background-repeat: no-repeat;
		box-shadow: 0 1px 2px 0 #E4E7EF;
		background-color: #ffffff;
		border: 1px solid #ffffff;
	}

	.toolItem:hover {
		border-color: #789CFF;
	}

	#delete {
		background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/delete.png');
	}

	.dialog-title {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		font-size: 18px;
	}
</style>
